import { ConfigProvider, Form, FormInstance, FormProps } from 'antd';
import cs from 'classnames';
import { isNil } from 'lodash-es';

import styles from './index.module.scss';

export type FilterProps<Values = any> = FormProps<Values> & {
  wrapperClassName?: string;
  extra?: React.ReactNode;
  formRef?: React.MutableRefObject<FormInstance<Values> | undefined>;
};

const Filter: React.FC<FilterProps> & {
  useForm: typeof Form.useForm;
  useFormInstance: typeof Form.useFormInstance;
  useWatch: typeof Form.useWatch;
  Item: typeof Form.Item;
  List: typeof Form.List;
  ErrorList: typeof Form.ErrorList;
  Provider: typeof Form.Provider;
  create: typeof Form.create;
} = <Values = any,>({
  className,
  wrapperClassName,
  extra,
  children,
  formRef,
  ...rest
}: FilterProps<Values>) => {
  return (
    <ConfigProvider
      theme={{
        components: {
          Form: {
            margin: 8
          }
        }
      }}
    >
      <div className={cs(styles['filter-wrapper'], wrapperClassName)}>
        <Form<Values>
          className={cs(styles['filter'], className)}
          // @ts-ignore
          children={
            children instanceof Function ? (values, form) => children(values, form) : children
          }
          layout="inline"
          {...rest}
        />

        {!isNil(extra) && <div className={styles['extra']}>{extra}</div>}
      </div>
    </ConfigProvider>
  );
};

Filter.useForm = Form.useForm;
Filter.useFormInstance = Form.useFormInstance;
Filter.useWatch = Form.useWatch;
Filter.Item = Form.Item;
Filter.List = Form.List;
Filter.ErrorList = Form.ErrorList;
Filter.Provider = Form.Provider;
Filter.create = Form.create;

export default Filter;
